package com.example.demo.web.manage.service;

import com.easy.query.api.proxy.client.EasyEntityQuery;
import com.easy.query.solon.annotation.Db;
import com.example.demo.web.manage.convert.DeptConvert;
import com.example.demo.web.manage.dto.DeptDto;
import com.example.demo.web.manage.model.DeptEntity;
import java.io.File;
import java.io.IOException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.annotation.*;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.UploadedFile;

/**
 * @author airhead
 */
@Component
@Slf4j
public class DeptService {
  @Db("db1")
  private EasyEntityQuery entityQuery;

  public List<DeptDto> list() {
    return entityQuery.queryable(DeptEntity.class).select(DeptDto.class).toList();
  }

  public Boolean add(DeptDto deptDto) {
    DeptEntity dept = DeptConvert.INSTANCE.convert(deptDto);

    return entityQuery.insertable(dept).executeRows(true) > 0L;
  }

  public Boolean update(DeptDto deptDto) {
    DeptEntity dept = DeptConvert.INSTANCE.convert(deptDto);
    return entityQuery.updatable(dept).executeRows() > 0L;
  }

  public DeptDto get(Long id) {
    return entityQuery
        .queryable(DeptEntity.class)
        .whereById(id)
        .select(DeptDto.class)
        .firstOrNull();
  }

  public Boolean delete(Long id) {
    return entityQuery
            .getEasyQueryClient()
            .deletable(DeptEntity.class)
            .allowDeleteStatement(true)
            .whereById(id)
            .executeRows()
        > 0L;
  }

  public Boolean importData(UploadedFile file) {
    try {
      log.info(file.getName());

      // 把它转为本地文件
      file.transferTo(new File(file.getName()));
    } catch (IOException e) {
      throw new RuntimeException(e);
    } finally {
      try {
        file.delete();
      } catch (IOException ignore) {
      }
    }

    return true;
  }

  public void exportData(Context context) {
    File file = new File("logo.png");
    try {
      context.outputAsFile(file);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
}
